<?php


namespace App\Models;


class ApiResult
{
    /**
     * @var int|number
     */
    public $code;

    /**
     * @var null|string
     */
    public $msg;

    /**
     * @var null
     */
    public $data;


    public function __construct($code = 200, $msg = '', $data = null)
    {
        $msg = __($msg);

        $this->code = $code;
        $this->msg = $msg;
        $this->data = $data;
    }

    /**
     * @return int|number
     */
    public function code()
    {
        return $this->code;
    }

    /**
     * @return null|string
     */
    public function message()
    {
        return $this->msg;
    }

    /**
     * @return null|\stdClass
     */
    public function data()
    {
        return $this->data;
    }

    /**
     * @return boolean
     */
    public function isSuccess()
    {
        return $this->code == 200;
    }

    /**
     * @return boolean
     */
    public function isFailure()
    {
        return !$this->isSuccess();
    }

    /**
     * @param $data
     * @param string $msg
     * @return ApiResult
     */
    public static function success($data, $msg = '操作成功')
    {
        return new ApiResult(200, $msg, $data);
    }

    /**
     * @param int $code
     * @param string $msg
     * @param null $data
     * @return ApiResult
     */
    public static function failure($code = 500, $msg = '操作失败', $data = null)
    {
        return new ApiResult($code, $msg, $data);
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return json_encode($this, JSON_UNESCAPED_UNICODE);
    }
}
